package com.fractal;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;

public class GetDatabase 
{
	private int drawBookmarks;
	private int version;
	private ArrayList<Double> xs;
	private ArrayList<Double> ys;
	private ArrayList<Double> sizes;
	
	public GetDatabase()
	{
		xs = new ArrayList<Double>();
		ys = new ArrayList<Double>();
		sizes = new ArrayList<Double>();
		updater.execute();
	}

	public GetDatabase(BufferedInputStream bis, SharedPreferences prefs) throws IOException
	{
		
		xs = new ArrayList<Double>();
		ys = new ArrayList<Double>();
		sizes = new ArrayList<Double>();
		if(bis!=null)
			load(bis, prefs);
		updater.execute();
	}
	
	public void load(BufferedInputStream bis, SharedPreferences prefs) throws IOException
	{
		drawBookmarks = prefs.getInt("enableBookmarks", 0);
		version = prefs.getInt("version", 0);
		
		byte[] buf = new byte[24];
		int count;
		while ( (count = bis.read(buf, 0, 24)) != -1)
		{
			if(count == 24)
			{
				ByteBuffer bbuf = ByteBuffer.wrap(buf);
				xs.add(bbuf.getDouble());
				ys.add(bbuf.getDouble());
				sizes.add(bbuf.getDouble());
			}
		}
	}
	
	public void save(FileOutputStream outStream, SharedPreferences prefs) throws IOException 
	{
		SharedPreferences.Editor editor;
		editor = prefs.edit();
		editor.putInt("enableBookmarks", drawBookmarks);
		editor.putInt("version", version);
		editor.commit();
		
		ByteBuffer buf = ByteBuffer.allocate(xs.size()*3*8);
		
		for(int i = 0, j = -1; i < xs.size(); i++)
		{
			buf.putDouble(xs.get(i));
			buf.putDouble(ys.get(i));
			buf.putDouble(sizes.get(i));
		}
		
		outStream.write(buf.array());
		outStream.flush();
	}
	
	public int toggle()
	{
		drawBookmarks ^= 1;
		return drawBookmarks;
	}
	
	public void getIntersection(ArrayList<Double> xsOut, ArrayList<Double> ysOut, 
								   double psize, double x0, double y0, double width, double height)
	{
		if (drawBookmarks == 1)
		{
			double x;
			double y;
			for (int i = 0; i < xs.size(); i++) 
			{
				x = xs.get(i);
				y = ys.get(i);
				
				if ((psize >= sizes.get(i)) &&  // tegn ikke markører der er zoomet forbi
				   (x0 < x) && (x < x0+width) && (y0 > y) && (y > y0-height)) // test at markøren ligger inden for tegne pladen
				{
					xsOut.add(x);
					ysOut.add(y);
				}
			}
		}
	}
	
	public void setMark(double x, double y, double size)
	{
		
		if (!xs.contains(x) || !ys.contains(y) || !sizes.contains(size))
		{
			xs.add(x);
			ys.add(y);
			sizes.add(size);
		}
	}
	
	private final AsyncTask<Void, Void, String> updater = new AsyncTask<Void, Void, String>()
	{
		@Override
		protected String doInBackground(Void... params) 
		{
			String res = "";
			String url = "http://www.kilza.dk/smap/index.php";
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(url);
	        try 
	        {
	        	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
		        nameValuePairs.add(new BasicNameValuePair("command", "update"));
		        nameValuePairs.add(new BasicNameValuePair("version", String.valueOf(version)));
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

		        HttpResponse response = httpclient.execute(httppost);
		        
				res = EntityUtils.toString(response.getEntity());
			} 
	        catch (ParseException e) 
	        {
	        	e.printStackTrace();
	        } 
	        catch (IOException e) 
	        {
	        	e.printStackTrace();
	        }
	        Log.d("debug", "doInBackground()");
	        return res;
		}

		@Override
		protected void onPostExecute(String result) 
		{
			super.onPostExecute(result);
			Log.d("debug", "onPostExecute()");
			double x, y , size;
        	JSONObject jObject;
			try 
			{
				jObject = new JSONObject(result);
				JSONArray items = jObject.getJSONArray("up"); 

				for (int i = 0; i < items.length(); i++) 
				{
					x = Double.valueOf(items.getJSONObject(i).getString("x0"));
					y = Double.valueOf(items.getJSONObject(i).getString("y0"));
					size =Double.valueOf(items.getJSONObject(i).getString("psize"));
					
					if (!xs.contains(x) || !ys.contains(y) || !sizes.contains(size))
					{
						xs.add(x);
						ys.add(y);
						sizes.add(size);
					}
				}
				version = Integer.valueOf(jObject.getString("ver"));
			} catch (JSONException e) {
				e.printStackTrace();
			} 
		}
	};

}
